<!-- 角色编辑弹窗 -->
<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer">
      <template v-slot:title>
        <span class="hLabel">{{
          isUpdate ? '修改轮播图设置' : '添加轮播图设置'
        }}</span>
      </template>
      <div class="ele-body">
        <el-card shadow="never">
          <div class="flex-column-between height83">
            <el-form ref="form"
                     :model="form"
                     label-width="100px"
                     :rules="rules">

              <el-form-item label="跳转类型:"
                            prop="type">
                <el-radio-group v-model="form.type">
                  <el-radio :label="1"
                            :value="1">首页</el-radio>
                  <el-radio :label="2"
                            :value="2">商城</el-radio>
                  <el-radio :label="3"
                            :value="3">套餐</el-radio>
                </el-radio-group>

              </el-form-item>
              <el-form-item prop="jump_way"
                            label="跳转类型:">
                <el-radio-group v-model="form.jump_way">
                  <!-- <el-radio :label="1"
                            :value="1">跳本地</el-radio> -->
                  <el-radio :label="2"
                            :value="2">跳h5</el-radio>
                  <!-- <el-radio :label="3"
                            :value="3">跳小程序</el-radio> -->
                </el-radio-group>

              </el-form-item>
              <el-form-item v-if="form.jump_way==1"
                            label="本地路径:"
                            prop="link">
                <el-input clearable
                          :maxlength="100"
                          v-model="form.link"
                          placeholder="请选择本地路径">
                </el-input>
              </el-form-item>
              <el-form-item v-if="form.jump_way==2"
                            label="跳转链接:"
                            prop="link">
                <el-input clearable
                          :maxlength="100"
                          v-model="form.link"
                          placeholder="请选择跳转链接">
                </el-input>
              </el-form-item>

              <div v-if="form.jump_way==3">
                <el-form-item label="原始ID:"
                              prop="applet_id">
                  <el-input clearable
                            :maxlength="100"
                            v-model="form.applet_id"
                            placeholder="请选择小程序原始ID">
                  </el-input>
                </el-form-item>
                <el-form-item label="小程序路径:"
                              prop="link">
                  <el-input clearable
                            :maxlength="100"
                            v-model="form.link"
                            placeholder="请选择小程序路径">
                  </el-input>
                </el-form-item>
              </div>

              <el-form-item label="排序值:"
                            prop="sort">
                <span slot="label">
                  排序值
                  <el-tooltip placement="top">
                    <div slot="content">
                      用于前端展示排序， 值越小排在前面
                    </div>
                    <i class="el-icon-question" />
                  </el-tooltip>
                </span>
                <el-input clearable
                          type="number"
                          step="1"
                          v-model="form.sort"
                          placeholder="请输入排序值" />
              </el-form-item>

              <!-- 提交图片 -->
              <el-form-item label="上传轮播图:"
                            prop="loopPicture">
                <el-upload action="#"
                           :on-exceed="exceedFn"
                           list-type="picture-card"
                           :file-list="fileList"
                           :limit="1"
                           :on-change="
                    (files, fileList) => handleFileChange(files, fileList)
                  "
                           :auto-upload="false">
                  <i slot="default"
                     class="el-icon-plus"></i>
                  <div slot="file"
                       slot-scope="{ file }">
                    <img class="el-upload-list__item-thumbnail"
                         :src="file.url"
                         alt="" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview"
                            @click="handlePictureCardPreview()">
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span class="el-upload-list__item-delete"
                            @click="handleDownload(file)">
                        <i class="el-icon-download"></i>
                      </span>
                      <span class="el-upload-list__item-delete"
                            @click="handleRemove(file)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
              </el-form-item>
            </el-form>
            <div class="drawer__footer">
              <el-button round
                         type="plain"
                         @click="handleClose"
                         size="medium">返回</el-button>
              <el-button type="primary"
                         round
                         :loading="loading"
                         size="medium"
                         @click="save">确定</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
  </div>
</template>

<script>

import ElImageViewer from 'element-ui/packages/image/src/image-viewer';


// import axios from 'axios';
import { upload } from '@/api/saveImg/index'
import { addPoster, editPoster } from '@/api/HomePageSettings/index'
export default {
  name: 'pictureEdit',
  components: { ElImageViewer },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },
  data () {
    const loopPicture = (rule, value, callback) => {
      console.log(this.form.img);
      if (!this.form.img) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    const DEFAULT_FORM = {
      // 展示区域  1 首页 2 商城 3 套餐卡市场
      type: 1,
      jump_way: 2,
      // 跳转链接
      link: '',
      // 排序
      sort: '',
      // 图片
      img: '',
      // 跳转方式 1 跳本地 ， 2 跳h5 ，3 跳小程序


      applet_id: ''

    };
    return {
      imgViewArr: [],
      viewerVisible: false,
      options: [],
      imageUrl: '',
      // 表单数据
      form: { ...DEFAULT_FORM },
      dialogImageUrl: '',
      fileList: [],
      dialogVisible: false,
      // 表单验证规则
      rules: {
        loopPictureType: [
          {
            required: true,
            message: '请填写轮播图类型',
            trigger: 'blur'
          }
        ],
        jumpType: [
          {
            required: true,
            message: '请输入跳转类型',
            trigger: 'blur'
          }
        ],
        // applet_id: [
        //   {
        //     required: true,
        //     message: '请输入小程序原始ID',
        //     trigger: 'blur'
        //   }
        // ],
        link: [
          {
            required: true,
            message: '请输入跳转链接',
            trigger: 'blur'
          }
        ],
        sort: [
          {
            required: true,
            message: '请填写排序号',
            trigger: 'blur'
          }
        ],
        showStatus: [
          {
            required: true,
            message: '请输入是否展示状态',
            trigger: 'blur'
          }
        ],
        // 站点 图片上传
        loopPicture: [
          { required: true, validator: loopPicture, trigger: 'change' }
        ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false
    };
  },
  computed: {
    // 营业执照
    urlListArray () {
      return this.imgViewArr;
    },
    // ** 隐私部分带*号
    hiddenCardId () {
      return function (str, frontLen = 4, endLen = 4) {
        //str：要进行隐藏的变量  frontLen: 前面需要保留几位    endLen: 后面需要保留几位
        var len = str.length - frontLen - endLen;
        var start = '';
        for (var i = 0; i < len; i++) {
          start += '*';
        }
        // 最后的返回值由三部分组成
        return (
          str.substring(0, frontLen) +
          start +
          str.substring(str.length - endLen)
        );
      };
    },
    //  code码获取城市标题
    // getRegionLabel () {
    //   return function (params) {
    //     console.log(cityData);
    //     return getRegionLabel(params);
    //   };
    // }
  },
  activated () {

  },
  methods: {
    // 点击按钮预览图片
    handlePictureCardPreview () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },
    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },
    // 删除图片
    handleRemove () {
      this.fileList = [];
      this.imageUrl = '';
      this.form.img = '';
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },

    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    },

    async handleFileChange (file, fileList) {
      console.log(file, fileList);
      this.loading = true;

      let files = file.raw;

      console.log(files)
      // 构建请求参数
      let params = new FormData();
      console.log(params);

      //   params.append('signature', '132321313');
      params.append('file', files);
      console.log(params);

      //   let config = {
      //     headers: {
      //       'Access-Control-Allow-Origin': '*',
      //       'x-oss-callback-Authorization': getToken()
      //     }
      //   };

      const res = await upload(params);
      //   let result = await axios.post(res.host, param, config);
      //   let url = res.host + '/' + date + suffix;
      console.log(res);
      if (res.code == 0) {
        this.form.img = res.data.url
        this.loading = false;
      }
    },

    // 阿里云
    // async aliFn (file, fileList) {
    //   this.loading = true;
    //   const res = await userOssSignature();
    //   let files = file.raw;
    //   let filename = file.name;
    //   let markIndex = filename.lastIndexOf('.');
    //   let suffix = filename.substring(markIndex);
    //   let date = new Date().getTime();
    //   // 构建请求参数
    //   let param = new FormData();
    //   param.append('key', date + suffix);
    //   param.append('policy', res.policy);
    //   param.append('OSSAccessKeyId', res.accessId);
    //   param.append('success_action_status', '200');
    //   // param.append("callback",  this.data.callback)     //回调（not)
    //   param.append('signature', res.signature);
    //   param.append('file', files, files.name);
    //   param.append('success_action_status', '200');
    //   let config = {
    //     headers: {
    //       'Access-Control-Allow-Origin': '*',
    //       'x-oss-callback-Authorization': getToken()
    //     }
    //   };
    //   console.log('suffix', suffix);

    //   let result = await axios.post(res.host, param, config);
    //   let url = res.host + '/' + date + suffix;
    //   console.log(url);
    //   this.imageUrl = url;
    //   this.form.img = url;
    //   this.loading = false;
    // },
    // async qnyFn (file, fileList) {
    //   this.loading = true;
    //   console.log(file, fileList);

    //   let files = file.raw;
    //   console.log(files);
    //   //   // 构建请求参数
    //   let param = new FormData();

    //   param.append('file', files, files.name);
    //   param.append('getsize', files.size);
    //   param.append('getContentType', files.type);
    //   param.append('getoriginalfilename', files.name);
    //   param.append('getName', files.name);

    //   const res = await qnyOssSignature(param);
    //   console.log(res.url);
    //   this.imageUrl = res.url;
    //   this.form.img = res.url;
    //   console.log('上传图片成功=======', res);
    //   this.loading = false;
    // },

    /* 保存编辑 */
    save () {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }
        const data = {
          ...this.form
        };
        console.log(data);
        this.loading = true;
        data.loopPicture = this.imageUrl;
        const saveOrUpdate = this.isUpdate
          ? editPoster
          : addPoster;
        saveOrUpdate(data)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg);

            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    }
    /* 更新visible */
  },
  watch: {
    drawerEditBoolen: {
      immediate: true,
      handler (visible) {
        console.log(visible);
        if (visible) {
          console.log(this.data);
          if (this.data) {
            this.form.id = '';
            console.log(this.$util);
            this.$util.assignObject(this.form, {
              ...this.data
            });
            console.log(this.form.img);
            if (this.form.img) {
              this.imageUrl = this.form.img;
              let markIndex = this.form.img.lastIndexOf('.');
              let suffix = this.form.img.substring(markIndex);
              if (!this.fileList.length) {
                this.fileList.push({
                  name: suffix,
                  url: this.form.img
                });
              } else {
                this.fileList = [
                  {
                    name: suffix,
                    url: this.form.img
                  }
                ];
              }
            } else {
              this.fileList = [];
            }

            this.isUpdate = true;
          } else {
            this.isUpdate = false;
            this.$util.assignObject(this.form, {
              ...this.data
            });
            this.form.type = 1
            this.form.jump_way = 1

            this.$nextTick(() => {
              this.$refs['form'].resetFields();
              this.handleRemove();

              console.log(this.form);
            });
          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
          });
        }
      }
    }
  }
};
</script>

<style lang="less" scoped>
::v-deep .el-upload-list__item {
  transition: none !important;
  -webkit-transition: nonne !important;
}
::v-deep .el-upload-list__item-name {
  transition: none !important;
  -webkit-transition: nonne !important;
}
/*隐藏input（type=number)右边的小箭头*/
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.height83 {
  height: 83vh;
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
}
</style>
